package ynu.edu.elmspringboot.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ynu.edu.elmspringboot.po.Cart;
import ynu.edu.elmspringboot.service.CartService;
import ynu.edu.elmspringboot.utils.PageResult;

import java.util.List;

@RestController
@RequestMapping("/CartController")
@Slf4j
@Api(tags = "购物车管理")
public class CartController {
    @Autowired
    private CartService cartService;

    @ApiOperation("根据用户id查询购物车信息")
    @PostMapping("/listCart")
    public List<Cart> listCart(String userId) {
        return cartService.listCart(userId);
    }

    @ApiOperation("保存购物车信息")
    @PostMapping("/saveCart")
    public int saveCart(Cart cart) {
        if (cart.getQuantity() == null) {
            cart.setQuantity(1); // 设置默认值
        }

        return cartService.save(cart) ? 1 : 0;
    }

    @ApiOperation("更新购物车信息")
    @PostMapping("/updateCart")
    public int updateCart(Cart cart) {
        // 打印接收到的参数
        log.info("Updating cart: {}", cart);

        // 验证必要字段
        if (cart.getCartId() == null || cart.getQuantity() == null) {
            return 0;
        }

        // 确保数量大于0
        if (cart.getQuantity() <= 0) {
            return 0;
        }

        return cartService.updateById(cart) ? 1 : 0;
    }

    @ApiOperation("删除购物车信息")
    @PostMapping("/removeCart")
    public int removeCart(Cart cart) {
        // 确保quantity为0
        cart.setQuantity(0);
        return cartService.removeCart(cart);
    }

    @ApiOperation("分页查询用户购物车")
    @GetMapping("/getCartPage")
    public PageResult<Cart> getCartPage(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("用户ID") @RequestParam String userId,
            @ApiParam("商家ID") @RequestParam(required = false) Integer businessId) {
        
        Page<Cart> page = new Page<>(current, size);
        IPage<Cart> result = cartService.getCartPage(page, userId, businessId);
        return PageResult.fromIPage(result);
    }

    @ApiOperation("分页查询购物车（包含关联的食品和商家信息）")
    @GetMapping("/getCartPageWithDetails")
    public PageResult<Cart> getCartPageWithDetails(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("用户ID") @RequestParam String userId) {
        
        Page<Cart> page = new Page<>(current, size);
        IPage<Cart> result = cartService.getCartPageWithDetails(page, userId);
        return PageResult.fromIPage(result);
    }
}
